import { Article } from './home'

type InitType = {
  suggestion: string[]
  // 存放历史记录的列表
  histories: string[]
  // 存放搜索结果
  results: Article[]
}

export type SearchAction =
  | {
      type: 'search/saveSuggestions'
      payload: string[]
    }
  | {
      type: 'search/clearSuggestions'
    }
  | {
      type: 'search/saveHistories'
      payload: string[]
    }
  | {
      type: 'search/clearHistories'
    }
  | {
      type: 'search/saveSearchResults'
      payload: Article[]
    }

const initValue: InitType = {
  suggestion: [],
  histories: [],
  results: [],
}

export default function reducer(state = initValue, action: SearchAction) {
  if (action.type === 'search/saveSuggestions') {
    return {
      ...state,
      suggestion: action.payload,
    }
  }
  if (action.type === 'search/clearSuggestions') {
    return {
      ...state,
      suggestion: [],
    }
  }
  if (action.type === 'search/saveHistories') {
    return {
      ...state,
      histories: action.payload,
    }
  }
  if (action.type === 'search/clearHistories') {
    return {
      ...state,
      histories: [],
    }
  }
  if (action.type === 'search/saveSearchResults') {
    return {
      ...state,
      results: [...state.results, ...action.payload],
    }
  }
  return state
}
